package com.itheima.delaytask.controller;

import com.itheima.delaytask.dto.Task;
import com.itheima.delaytask.service.TaskService;
import com.itheima.response.ResponseMessage;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.*;

/**
 * Created by 传智播客*黑马程序员.
 */
@Slf4j
@RestController
@RequestMapping("/task")
public class TaskController {
    
    @Autowired
    private TaskService taskService;
    
    @PostMapping("/push")
    public ResponseMessage pushTask(@RequestBody Task task) {
        log.info("add task,task={}", task);
        //参数校验
        Assert.notNull(task.getTaskType(), "任务类型不能为空");
        Assert.notNull(task.getPriority(), "任务优先级不能为空");
        Assert.notNull(task.getExecuteTime(), "任务执行时间不能为空");
        long taskId = taskService.addTask(task);
        return ResponseMessage.ok(taskId);
    }
    
    @GetMapping("/poll/{type}/{priority}")
    public ResponseMessage pollTask(@PathVariable("type") Integer type, @PathVariable("priority") Integer priority) {
        log.info("poll task {},{}", type, priority);
        //参数校验
        Assert.notNull(type, "任务类型不能为空");
        Assert.notNull(priority, "任务优先级不能为空");
        Task task = taskService.poll(type, priority);
        return ResponseMessage.ok(task);
    }
    
    @PostMapping("/cancel")
    public ResponseMessage cancelTask(@RequestParam("taskId") Long taskId) {
        log.info("cancel task,taskId={}", taskId);
        boolean cancelTask = taskService.cancelTask(taskId);
        return ResponseMessage.ok(cancelTask);
    }
    
    @GetMapping("/refresh")
    public ResponseMessage refresh() {
        log.info("refresh----");
        taskService.refresh();
        return ResponseMessage.ok(null);
    }
    
}
